package cn.acac.yygh.cmn.service.impl;

import cn.acac.yygh.cmn.listener.DictListener;
import cn.acac.yygh.cmn.mapper.DictMapper;
import cn.acac.yygh.cmn.service.DictService;
import cn.acac.yygh.model.cmn.Dict;
import cn.acac.yygh.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class DictServiceImpl
        extends ServiceImpl<DictMapper,Dict>
        implements DictService {

    /**
     * 根据父id查询所有的子节点
     * @param pid
     * @return
     */
    @Override
    public List<Dict> findChildData(Long pid) {
        // 添加查询条件
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        // 进行查询
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        return dictList;
    }

    /**
     * 判断子节点是否还有子节点
     * @param pid
     * @return
     */
    @Override
    public boolean hasChildren(Long pid) {
        // 添加查询条件
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        // 进行查询
        Integer count= baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 导入Excel文件
     * @param file
     */
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void updateExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(this.baseMapper))
                .sheet(0).doRead();
    }

    /**
     * 医院服务调用字典服务查询信息
     * @param value
     * @return
     */
    @Override
    public String findNameByValue(String value) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("value",value);
        Dict dict = baseMapper.selectOne(queryWrapper);
        return dict.getName();
    }

    /**
     * 医院服务调用字典服务查询信息
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String findNameByValue(String dictCode, String value) {
        // 首先根据dictCode查询医院信息
        // 第一次查询
        QueryWrapper<Dict> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("dict_code",dictCode);
        Dict dict1 = baseMapper.selectOne(queryWrapper1);

        // 第二次查询
        QueryWrapper<Dict> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("parent_id",dict1.getId());
        queryWrapper2.eq("value",value);
        Dict dict2 = baseMapper.selectOne(queryWrapper2);
        return dict2.getName();
    }
}
